<template>
  <a-modal
    :title="title"
    :width="720"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item label="课程名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['name', { rules: [{ required: true, min: 2, message: '请输入至少2个字符' }] }]"
            placeholder="请输入课程名称"
          />
        </a-form-item>
        <a-form-item label="课程icon" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <SelectImage :defaultList="record.image ? [record.image] : []" v-decorator="['image_id', { rules: [{ required: true, message: '请至少上传1张课程icon' }] }]" />
        </a-form-item>
        <a-form-item label="课时" :labelCol="labelCol" :wrapperCol="wrapperCol" help="一共多少节课">
          <a-input-number
            :min="1"
            v-decorator="['lessons', { initialValue: 10, rules: [{ required: true, message: '请填写一共多少节课' }] }]"
          />
        </a-form-item>
        <a-form-item label="每课时长度" :labelCol="labelCol" :wrapperCol="wrapperCol" help="一节课时长多少">
          <a-input-number
            :min="1"
            v-decorator="[
              'class_hour',
              { initialValue: 10, rules: [{ required: true, message: '请填写单节课的时长' }] },
            ]"
          />
        </a-form-item>
        <a-form-item label="开班人数" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number
            :min="1"
            v-decorator="['class_size', { initialValue: 10, rules: [{ required: true, message: '请填写开班人数' }] }]"
          />
        </a-form-item>
        <a-form-item label="开班日期" :labelCol="labelCol" :wrapperCol="{ span: 16 }">
          <a-range-picker
            v-decorator="['opening_date', { rules: [{ required: true, message: '请选择开班日期' }] }]"
          />
        </a-form-item>
        <a-form-item label="课程详情" :labelCol="labelCol" :wrapperCol="{ span: 16 }">
          <a-textarea
            v-decorator="['course_detail', { rules: [{ required: true, message: '课程详情不能为空' }] }]"
            placeholder="请填写课程详情"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
        <a-form-item label="上课时间" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="默认的上课时间">
          <class-time v-decorator="['class_time', { rules: [{ required: true, message: '请选择一个时间段' }] }]" />
        </a-form-item>
        <a-form-item label="上课地点" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="默认的上课地点">
          <a-input
            v-decorator="['class_place', { rules: [{ required: true, min: 2, message: '请输入至少2个字符' }] }]"
            placeholder="请填写上课地点"
          />
        </a-form-item>
        <a-form-item label="课程教练" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            v-decorator="['employee_ids', { rules: [{ required: true, message: '请选择一个课程教练!' }] }]"
            placeholder="请选择一个课程教练"
            mode="multiple"
          >
            <template v-for="coach in coachList">
              <a-select-option :value="coach.employee_id" :key="coach.employee_id"> {{ coach.name }} </a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="价格" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number
            :min="1"
            v-decorator="['price', { initialValue: 100, rules: [{ required: true, message: '请填写价格' }] }]"
          />
        </a-form-item>
        <a-form-item label="推荐状态" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="开启后会在首页显示">
          <a-switch v-decorator="['recommend', { valuePropName: 'checked', initialValue: false }]" />
        </a-form-item>
        <a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            v-decorator="['status', { rules: [{ required: true, message: '请选择一个状态!' }] }]"
          >
            <a-select-option :value="0"> 下架 </a-select-option>
            <a-select-option :value="1"> 上架 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" extra="数字越小越靠前">
          <a-input-number
            :min="0"
            v-decorator="['sort', { initialValue: 10, rules: [{ required: true, message: '请输入至少1个数字' }] }]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import _ from 'lodash'
import * as CourseApi from '@/api/course/index'
import * as CoachApi from '@/api/course/coach'
import ClassTime from './ClassTime'
import { SelectImage } from '@/components'
import moment from 'moment'

export default {
  props: {},
  components: {
    ClassTime,
    SelectImage,
  },
  data() {
    return {
      // 对话框标题
      title: '',
      // 标签布局属性
      labelCol: {
        span: 7,
      },
      // 输入框布局属性
      wrapperCol: {
        span: 13,
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 当前记录
      record: {},
      // 教练列表
      coachList: [],
    }
  },
  methods: {
    /**
     * 显示对话框
     */
    edit(item) {
      // 显示窗口
      this.title = '编辑课程'
      this.visible = true
      this.record = item
      // 获取教练列表
      this.getAllCoach()
      // 设置默认值
      this.setFieldsValue()
    },

    /**
     * 获取教练列表
     */
    getAllCoach() {
      CoachApi.all().then((res) => {
        this.coachList = res.data
      })
    },

    /**
     * 设置默认值
     */
    setFieldsValue() {
      const {
        form: { setFieldsValue },
      } = this
      this.$nextTick(() => {
        const data = _.pick(this.record, [
          'name',
          'lessons',
          'class_hour',
          'class_size',
          'opening_date',
          'course_detail',
          'class_time',
          'image_id',
          'price',
          'recommend',
          'status',
          'class_place',
          'sort',
        ])
        const dateArr = data['opening_date'].split('~')
        data['opening_date'] = [moment(dateArr[0], "YYYY-MM-DD"), moment(dateArr[1], "YYYY-MM-DD")]
        data['recommend'] = data['recommend'] == 1
        data['employee_ids'] = this.record.coachs.map(coach => coach.employee_id)
        console.log(data)
        
        setFieldsValue(data)
      })
    },

    /**
     * 确认按钮
     */
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        const opening_date = [values.opening_date[0].format("YYYY-MM-DD"), values.opening_date[1].format("YYYY-MM-DD")].join('~')
        values.recommend = values.recommend ? 1:0
        !errors && this.onFormSubmit({...values, opening_date})
      })
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.confirmLoading = true
      CourseApi.edit({...values, 'course_id': this.record.course_id})
        .then((result) => {
          // 显示成功
          this.$message.success(result.message, 1.5)
          // 关闭对话框事件
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally((result) => {
          this.confirmLoading = false
        })
    },

    /**
     * 关闭对话框事件
     */
    handleCancel() {
      this.visible = false
      this.form.resetFields()
    },
  },
}
</script>
